const os = require('os')

const gulp = require('gulp'),
  babel = require('gulp-babel'),
  browserify = require('gulp-browserify'),
  uglify = require('gulp-uglify'),
  del = require('del'),
  less = require('gulp-less'),
  sourcemaps = require('gulp-sourcemaps'),
  minifyCSS = require('gulp-clean-css'),
  rename = require('gulp-rename'),
  sequence = require('gulp-sequence'),
  fileInclude = require('gulp-file-include'),
  open = require('gulp-open'),
  concat = require('gulp-concat'),
  connect = require('gulp-connect'),
  autoprefixer = require('gulp-autoprefixer'),
  replace = require('gulp-replace'),
  flatten = require('gulp-flatten'),
  htmlmin = require('gulp-htmlmin')

const PREFIX = '^^static_url',
  // 开发路径
  DEV_URL = '..',
  // 线上环境
  PRO_URL = '..',
  TITLE_PREFIX = '^^title',
  TITLE = '壹平方米',
  // 详情页标题宽度(24栅格占比)
  GUTTER_NAME_PREFIX = '^^gutter-name',
  GUTTER_VALUE_PREFIX = '^^gutter-value',
  GUTTER_COUNT = 24,
  GUTTER_NAME = 8,
  GUTTER_VALUE = GUTTER_COUNT - GUTTER_NAME

function getIp () {
  const arr = os.networkInterfaces()
  const ipArr = []

  for (let v in arr) {
    arr[v].forEach(_v => {
      if (_v.family === 'IPv4') {
        ipArr.push(_v.address)
      }
    })
  }

  return ipArr
}

const port = '8454'

/* 清空文件夹 */
gulp.task('clean', () => {
  return (
    del('./dist/**/*')
  )
})

/* html */
gulp.task('html', () => {
  return (
    gulp.src([
      './src/html/index.html',
      './src/html/login.html',
      './src/html/maintenance.html',
      './src/html/!(public)/**/*.html'
    ])
      .pipe(fileInclude({
        prefix: '@@',
        basepath: './src/html/public/'
      }))
      .pipe(replace(PREFIX, DEV_URL))
      .pipe(replace(TITLE_PREFIX, TITLE))
      .pipe(replace(GUTTER_NAME_PREFIX, GUTTER_NAME))
      .pipe(replace(GUTTER_VALUE_PREFIX, GUTTER_VALUE))
      .pipe(gulp.dest('./dist/'))
      .pipe(connect.reload())
  )
})

/* js */
gulp.task('js', () => {
  return (
    gulp.src([
      './src/js/!(data|public|vendor)/*.js'
    ])
      .pipe(sourcemaps.init())
      .pipe(babel())
      .pipe(browserify({
        transform: ['babelify']
      }))
      .pipe(sourcemaps.write())
      // .pipe(uglify())
      .pipe(flatten())
      .pipe(gulp.dest('./dist/js'))
      .pipe(connect.reload())
  )
})

/* jsVendor */
gulp.task('jsVendor', () => {
  return (
    gulp.src([
      './src/js/vendor/vue.min.js',
      './src/js/vendor/jquery-1.9.1.min.js',
      './src/js/vendor/underscore-min.js',
      './src/js/vendor/moment.min.js',
      './src/js/vendor/bootstrap.min.js',
      './src/js/vendor/bootstrap-table.min.js',
      './src/js/vendor/bootstrap-table-zh-CN.min.js',
      './src/js/vendor/jquery.validate.min.js',
      './src/js/vendor/jquery.mCustomScrollbar.concat.min.js',
      './src/js/vendor/js.cookie.min.js',
      './src/js/vendor/selectize.min.js',
      './src/js/vendor/bootstrap-datetimepicker.min.js',
      './src/js/vendor/bootbox.min.js',
      './src/js/vendor/layer.js',
      './src/js/vendor/messages_zh.min.js',
      './src/js/vendor/qrcode.js',
      './src/js/vendor/vue-router.js',
      './src/js/vendor/wangEditor.js',
    ])
      .pipe(concat('vendor.js'))
      // .pipe(uglify())
      .pipe(gulp.dest('./dist/js/'))
      .pipe(connect.reload())
  )
})

/* font */
gulp.task('font', () => {
  return (
    gulp.src('./src/font/**')
      .pipe(gulp.dest('./dist/font'))
  )
})

/* img */
gulp.task('img', () => {
  return (
    gulp.src('./src/img/**')
      .pipe(gulp.dest('./dist/img'))
  )
})

/* less */
gulp.task('less', () => {
  return (
    gulp.src(['./src/less/1m2.less'])
    // .pipe(sourcemaps.init())
      .pipe(less())
      .pipe(autoprefixer({
        browsers: ['> 0.01%']
      }))
      .pipe(minifyCSS({
        advanced: false, // 默认：true [是否开启高级优化（合并选择器等）]
        compatibility: 'ie8', // 保留ie7及以下兼容写法 类型：String 默认：''or'*' [启用兼容模式； 'ie7'：IE7兼容模式，'ie8'：IE8兼容模式，'*'：IE9+兼容模式]
        keepBreaks: true,  // 类型：Boolean 默认：false [是否保留换行]
        keepSpecialComments: '*'    // 保留所有特殊前缀 当你用autoprefixer生成的浏览器前缀，如果不加这个参数，有可能将会删除你的部分前缀
      }))
      // .pipe(sourcemaps.write())
      .pipe(gulp.dest('./dist/css'))
      .pipe(connect.reload())
  )
})

/* css */
gulp.task('css', () => {
  return (
    gulp.src('./src/css/*.css')
      .pipe(minifyCSS({
        keepSpecialComments: '*'
      }))
      .pipe(concat('vendor.css'))
      .pipe(gulp.dest('./dist/css/'))
      .pipe(connect.reload())
  )
})

/* 服务器 */
gulp.task('connect', () => {
  connect.server({
    root: 'dist',
    host: getIp()[0],
    port: port,
    livereload: true
  })
})

/* 打开浏览器 */
gulp.task('open', () => {
  gulp.src(__filename)
    .pipe(open({
      uri: `http://${ getIp()[0] }:${ port }`,
      app: 'chrome'
    }))
})

/* watch */
gulp.task('watch', () => {

  gulp.watch('src/less/**/*.less', ['less'])
  gulp.watch(['src/**/*.html'], ['html'])
  gulp.watch(['src/css/**/*.css'], ['css'])
  gulp.watch(['src/js/data/**/*.js', 'src/js/public/**/*.js'], ['js'])
  gulp.watch(['src/js/vendor/**/*.js'], ['jsVendor'])

  return gulp.watch(['src/js/!(data|public|vendor)/*.js', 'src/js/index.js'], (e) => {

    gulp.src(e.path)
      .pipe(babel())
      .pipe(browserify({
        transform: ['babelify']
      }))
      // .pipe(uglify())
      .pipe(gulp.dest('./dist/js'))
      .pipe(connect.reload())

  })

})

gulp.task('default', ['clean'], () => {
  sequence('html', 'jsVendor', 'js', 'less', 'css', 'font', 'img', 'connect', 'open', 'watch')()
})

gulp.task('build', ['clean'], () => {
  sequence('html', 'jsVendor', 'js', 'less', 'css', 'font', 'img')()
})